/*********************************************************************/
/*  文件名  RadarProxy.java    　                                       */
/*  程序名  Radar Service代理                     						     			 */
/*  版本履历   2015/5/5  修改                  刘伟    			                             */
/*         Copyright 2015 LENOVO. All Rights Reserved.               */
/*********************************************************************/
package com.zhaolang.qogir.server;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.util.SparseArray;

import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.BaseResp;
//import com.zhaolang.qogir.domain.GetPostList.MPostResp;
//import com.zhaolang.qogir.domain.PostReleaseCallBack;
//import com.zhaolang.qogir.domain.PostReleaseCallBack.MPostImgResp;
//import com.zhaolang.qogir.domain.PostReleaseCallBack.PostReleaseReq;
//import com.zhaolang.qogir.domain.PostReleaseCallBack.UpdatePostSendingState;
//import com.zhaolang.qogir.domain.SolutionCreateUpdate;
//import com.zhaolang.qogir.domain.SolutionCreateUpdate.CoverImgResp;
//import com.zhaolang.qogir.domain.SolutionCreateUpdate.SolutionCreateReq;
//import com.zhaolang.qogir.domain.SolutionCreateUpdate.SolutionUpdateReq;
//import com.zhaolang.qogir.domain.SolutionCreateUpdate.TextImgResp;
//import com.zhaolang.qogir.domain.SolutionDetailData.MSolutionResp;
//import com.zhaolang.qogir.domain.SolutionListData;
//import com.zhaolang.qogir.domain.SolutionListData.SolutionDataGetDelete;
//import com.zhaolang.qogir.domain.SolutionListData.SolutionDataSave;
//import com.zhaolang.qogir.domain.impl.PostReleaseCallBackAsyncImpl;
//import com.zhaolang.qogir.domain.impl.SolutionCreateUpdateAsyncImpl;
//import com.zhaolang.qogir.textbuilder.BBSDescribeItem;
//import com.zhaolang.qogir.textbuilder.BBSTextBuilder;
//import com.zhaolang.qogir.textbuilder.impl.BBSTextBuilderImpl;
//import com.zhaolang.qogir.ui.Constants;
//import com.zhaolang.qogir.ui.topic.TopicHelper;
import com.zhaolang.qogir.util.GsonUtil;
import com.zhaolang.qogir.util.HttpConstant;
import com.zhaolang.qogir.util.Slog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class RadarProxy implements Handler.Callback {
	private final String TAG = "RadarProxy";
	private static RadarProxy instance;
	private CallbackMap mCallbackMap;
	private int callbackID;
	private IRadarServer mServer;
	private Handler mHandler;
	private Context mContext;
	//private ClientCallback clientCallback;

	private boolean needBinder = false;
	private boolean isBinding = false;
	private boolean bindService = false;
	private boolean serverIsNull = false;
	private String bindRemoteServerName = "com.zhaolang.qogir.server.RadarServer";

//	private PostReleaseCallBackAsyncImpl postRelease;
//	private SolutionCreateUpdateAsyncImpl solutionRelease;
//	private BBSTextBuilder mTextBuilder;
//	private BBSTextBuilder mTextBuilderSolution;
	
	// API STARTED

	public static RadarProxy getInstance(Context context) {
		if (instance == null) {
		   synchronized (RadarProxy.class) { 
		        if (instance == null) { 
		        	instance = new RadarProxy(context);
		        }
		    } 
		}
		return instance;
	}

	/**
	 * start bind Server called when UI creating if used
	 */
	public void bindServer() {
		needBinder = true;
		connectService();
	}

	/**
	 * unbindServer called when UI quit
	 */
	public void unBindServer() {
		needBinder = false;
		disconnectService();
	}

	/**
	 * set UI listener
	 */
	// public void setLinkListener(ILinkLIstener listener) {
	// this.mRdbListener = listener;
	// if(this.mRdbListener != null){
	// bindServer();
	// }
	// }

	// API END

	private RadarProxy(Context context) {
		this.mContext = context.getApplicationContext();
		mHandler = new Handler(this);
		mCallbackMap = new CallbackMap(20);
//		postRelease = new PostReleaseCallBackAsyncImpl(mContext);
//		solutionRelease = new SolutionCreateUpdateAsyncImpl(mContext);
	}

	private final int MSG_BIND_TIMEOUT = 1;
	private final int MSG_RESULT_CALLBACK = 2;

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MSG_BIND_TIMEOUT:
			isBinding = false;
			break;
		case MSG_RESULT_CALLBACK:
			try {
				Slog.d("handleMessage MSG_RESULT_CALLBACK msg: "+ msg);
				if (!mCallbackMap.isEmpty()) {
					ClientCallback clientCallback = mCallbackMap.getEntry(msg.arg1);
					if (clientCallback != null) {
						Slog.d("msg.obj.toString: " + msg.obj.toString());
						clientCallback.onSuccess(msg.obj.toString());
					} else {
						Slog.e("MSG_RESULT_CALLBACK: clientCallback is null");
					}
				} else {
					Slog.e("MSG_RESULT_CALLBACK: mCallbackMap is Empty");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
		return true;
	}

	private final int MSG_SERVER_ISNOTNULL = 0;
	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName arg0, IBinder arg1) {
			Slog.i("on RadarService Connected!");
			mServer = IRadarServer.Stub.asInterface(arg1);
			if (serverIsNull) {
				handler.sendEmptyMessage(MSG_SERVER_ISNOTNULL);
				serverIsNull = false;
			}
			bindService = true;
			isBinding = false;
			mHandler.removeMessages(MSG_BIND_TIMEOUT);
			registerCallback();
			startLocalData(HttpConstant.POST_RELEASE_UPDATE_STATE_ALL, null, null);
//			startLocalData(HttpConstant.POST_DETAIL_RESTORE_STATE_ALL, null, null);
//			SolutionDataSave saveBean = new SolutionDataSave();
//			saveBean.setType(SolutionListData.SOLUTION_SENDING_DATA);
//			saveBean.setSendState(SolutionCreateUpdate.SOLUTION_RELEASE_FAILED);
//        	startLocalData(HttpConstant.SOLUTION_STATE_UPDATE_BYTYPE, GsonUtil.getGson().toJson(saveBean), null);
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			Slog.i("on RadarService Disconnected!");
//			mServer = null;
			bindService = false;
			isBinding = false;
			mHandler.removeMessages(MSG_BIND_TIMEOUT);
			if (needBinder) {
				bindServer();
			}
		}

	};

	private void connectService() {
		if (mServer == null && !isBinding) {
			Intent intent = new Intent(mContext, RadarServer.class);// Intent(bindRemoteServerName);
			mContext.startService(intent);

			mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

			Slog.i("bind RadarServer Started!");
			isBinding = true;
			mHandler.removeMessages(MSG_BIND_TIMEOUT);
			mHandler.sendEmptyMessageDelayed(MSG_BIND_TIMEOUT, 5 * 1000);
		} else {
			Slog.w("connect RadarService rejected! mRemoteServer != null or isBinding : " + isBinding);
			if (mServer != null) {
				registerCallback();
			}
		}
	}

	private void disconnectService() {
		if (bindService) {
			try {
				unRegisterCallback();
				mContext.unbindService(mServiceConnection);
			} catch (Exception e) {
				Slog.e("disconnect RadarService Error!", e);
			}
			bindService = false;
			isBinding = false;
			mHandler.removeMessages(MSG_BIND_TIMEOUT);
		}
	}

	private void registerCallback() {
		try {
			if (mServer != null) {
				mServer.registerCallback(mIRadarCallback);
				Slog.i("register IRadarCallback successfully!");
			} else {
				connectService();
			}
		} catch (RemoteException e) {
			Slog.e("register IRadarCallback error : ", e);
			mServer = null;
			bindService = false;
			connectService();
		}
	}

	private void unRegisterCallback() {
		try {
			if (mServer != null) {
				mServer.unRegisterCallback();
				Slog.i("unRegister IRadarCallback successfully!");
			}
		} catch (RemoteException e) {
			Slog.e("unRegister IRadarCallback error : ", e);
		}
	}

	Handler handler;

	public void startServerData(final ServerRequestParams serverRequestParams, final ClientCallback cltCallback) {
		if (mServer == null) {
			serverIsNull = true;
			handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					switch (msg.what) {
					case MSG_SERVER_ISNOTNULL:
						startUpServer(serverRequestParams, cltCallback);
						break;
					default:
						break;
					}
				}
			};
			connectService();
		} else {
			startUpServer(serverRequestParams, cltCallback);
		}
	}

	private void startUpServer(ServerRequestParams serverRequestParams, ClientCallback cltCallback) {
		try {
			if (callbackID > 999999999) {
				callbackID = 0;
			}
			mServer.startUploadServer(serverRequestParams, ++callbackID);
			//RadarProxy.this.clientCallback = cltCallback;
			if (!mCallbackMap.isFull()) {
				if (cltCallback != null) {
					mCallbackMap.insert(callbackID, cltCallback);
				}
			} else {
				if (cltCallback != null) {
					String callback = resultStatus("{\"status\":\"FAILED\",\"msg\":\"call back queue is full\",\"ok\":true}", BaseResp.UNKNOWN, false);
					cltCallback.onSuccess(callback);
				}
			}
			Slog.d("startUpServer cltCallback: " + cltCallback + " callbackID: " + callbackID);
		}
		catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public void startLocalData(final String localRequestParams, final String localContent,
                               final ClientCallback cltCallback) {
		if (mServer == null) {
			serverIsNull = true;
			handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					switch (msg.what) {
						case MSG_SERVER_ISNOTNULL:
							startUpLocal(localRequestParams, localContent, cltCallback);
							break;
						default:
							break;
					}
				}
			};
			connectService();
		} else {
			startUpLocal(localRequestParams, localContent, cltCallback);
		}
	}
//
//    private void uploadImage(final PostReleaseReq bean, final List<BBSDescribeItem> images, int thumbSize, final int type) {
//        List<String> imageUrls = TopicHelper.describeItemContent2Strings(images);
//        if (Constants.COMPRESS_POST_IMAGE) {
//            List<String> compress = TopicHelper.compress(imageUrls);
//            if (compress != null && compress.size() == imageUrls.size()) {
//            	imageUrls.clear();
//                imageUrls.addAll(compress);
//            }
//        }
//        String log = "";// 打印LOG用的，把路径全都拼起来打印
//        if (imageUrls != null) {
//            for (String str : imageUrls) {
//                log += str + ", ";
//            }
//        }
//        Log.i("III_logic", "paths " + log);
//        if (imageUrls != null && imageUrls.size() == 0) {
//            // 一般是编辑的时候用到的，这个情况代表图片全都不是本地的，一般情况来说，也就是图片都是服务器的
//            List<String> thumbs = new ArrayList<String>();
//            if (imageUrls.size() != thumbSize) {
//                // 这个代表
//                List<BBSDescribeItem> imgs = TopicHelper.findImages(mTextBuilder);
//                for (int i = 0; i < imgs.size(); i++) {
//                    // 将服务的绝对地址改为相对地址
//                    thumbs.add(imgs.get(i).getContent().toString().replace(HttpConstant.OFFICIAL_RADAR_DOWNLOAD_IMG_IP, ""));
//                }
//                // 缩略图的地址
//            }
//
//            // 将空内容去掉，比如没有文字的文本框
//            TopicHelper.trimBBSTextBuilder(mTextBuilder);
//            if (type == 1) {
//            	releasePost(bean, mTextBuilder.getString(), thumbs);
//            } else if (type == 2) {
//            	updatePost(bean, mTextBuilder.getString(), thumbs);
//            }
//            Log.i("III_logic", "帖子中没有图片，或已上传成功");
//            return;
//        }
//        postRelease.uploadPostImgAsync(imageUrls, new BaseCall<MPostImgResp>() {
//            @Override
//            public void call(MPostImgResp resp) {
//                if (resp != null && resp.isRequestSuccess()) {
//                    // 第一步，判断服务器给的图片地址和本地上传的图片数量一样多
//                    if (resp.getPostImgURL() != null && resp.getPostImgURL().size() == images.size()) {
//
//                        // 将帖子中途地址全部换成服务器的地址
//                        TopicHelper.setStrings2BBSDescribeItemContent(resp.getPostImgURL(), images, ""/*HttpConstant.OFFICIAL_RADAR_DOWNLOAD_IMG_IP*/);
//                        TopicHelper.trimBBSTextBuilder(mTextBuilder);
//
//                        List<BBSDescribeItem> images = TopicHelper.findImages(mTextBuilder);
//                        List<String> thumbs = new ArrayList<String>(images.size());
//                        for (int i = 0; i < images.size(); i++) {
//                            thumbs.add(images.get(i).getContent().toString().replace(HttpConstant.OFFICIAL_RADAR_DOWNLOAD_IMG_IP, ""));
//                        }
//                        if (bean.getPostLevel() == 0) {
//                        	PostReleaseReq imgBean = analyzeBeanImg(bean, mTextBuilder.getString(), thumbs);
//                        	startLocalData(HttpConstant.POST_RELEASE_UPDATEIMG_ONE, GsonUtil.getGson().toJson(imgBean), null);
//                        } else if (bean.getPostLevel() == 1) {
//                        	PostReleaseReq imgBean = analyzeBeanImg(bean, mTextBuilder.getString(), thumbs);
//                        	startLocalData(HttpConstant.POST_DETAIL_UPDATEIMG_ONE, GsonUtil.getGson().toJson(imgBean), null);
//                        }
//
//                        if (type == 1) {
//                        	releasePost(bean, mTextBuilder.getString(), thumbs);
//                        } else if (type == 2) {
//                        	updatePost(bean, mTextBuilder.getString(), thumbs);
//                        }
//                        Slog.d("postReleaseBackground uploadImage sucess");
//                    } else {
//                    	Slog.d("postReleaseBackground uploadImage failed");
//                    	if (bean.getPostLevel() == 0) {
//                    		UpdatePostSendingState stateBean = new UpdatePostSendingState();
//                    		stateBean.setLocalPostId(bean.getLocalPostId());
//                    		stateBean.setLocalCreateTime(bean.getLocalCreateTime());
//                    		stateBean.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                        	startLocalData(HttpConstant.POST_RELEASE_UPDATE_STATE_ONE, GsonUtil.getGson().toJson(stateBean), null);
//                        } else if (bean.getPostLevel() == 1) {
//                        	UpdatePostSendingState stateBean = new UpdatePostSendingState();
//                    		stateBean.setLocalPostId(bean.getLocalPostId());
//                    		stateBean.setLocalCreateTime(bean.getLocalCreateTime());
//                    		stateBean.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                        	startLocalData(HttpConstant.POST_DETAIL_UPDATE_SENDING_STATE, GsonUtil.getGson().toJson(stateBean), null);
//                        }
//
//                    	MPostResp respFailed = new MPostResp();
//                    	respFailed.setSuccess(resp.isSuccess());//true,false
//                    	respFailed.setStatusCode(resp.getStatusCode());
//                    	respFailed.setMessage(resp.getMessage());
//                    	respFailed.setStatus(resp.getStatus());
//                    	respFailed.setLocalPostId(bean.getLocalPostId());
//                    	respFailed.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                    	Intent intent = new Intent();
//                    	intent.setAction(PostReleaseCallBack.MAINPOST_RELEASE_END);
//                    	Bundle bundle = new Bundle();
//                    	bundle.putSerializable("RespData", respFailed);
//                    	intent.putExtras(bundle);
//
//                        mContext.sendBroadcast(intent);
//                    }
//                } else {
//                	if (bean.getPostLevel() == 0) {
//                		UpdatePostSendingState stateBean = new UpdatePostSendingState();
//                		stateBean.setLocalPostId(bean.getLocalPostId());
//                		stateBean.setLocalCreateTime(bean.getLocalCreateTime());
//                		stateBean.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                    	startLocalData(HttpConstant.POST_RELEASE_UPDATE_STATE_ONE, GsonUtil.getGson().toJson(stateBean), null);
//                    } else if (bean.getPostLevel() == 1) {
//                    	UpdatePostSendingState stateBean = new UpdatePostSendingState();
//                		stateBean.setLocalPostId(bean.getLocalPostId());
//                		stateBean.setLocalCreateTime(bean.getLocalCreateTime());
//                		stateBean.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                    	startLocalData(HttpConstant.POST_DETAIL_UPDATE_SENDING_STATE, GsonUtil.getGson().toJson(stateBean), null);
//                    }
//
//                	MPostResp respFailed = new MPostResp();
//                	respFailed.setSuccess(resp.isSuccess());//true,false
//                	respFailed.setStatusCode(resp.getStatusCode());
//                	respFailed.setMessage(resp.getMessage());
//                	respFailed.setStatus(resp.getStatus());
//                	respFailed.setLocalPostId(bean.getLocalPostId());
//                	respFailed.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                	Intent intent = new Intent();
//                	intent.setAction(PostReleaseCallBack.MAINPOST_RELEASE_END);
//                	Bundle bundle = new Bundle();
//                	bundle.putSerializable("RespData", respFailed);
//                	intent.putExtras(bundle);
//
//                    mContext.sendBroadcast(intent);
//                    Slog.d("postReleaseBackground uploadImage failed");
//                }
//            }
//        });
//    }
//
//    private void releasePost(final PostReleaseReq bean, String content, List<String> imgs) {
//
//    	final PostReleaseReq relBean = analyzeBeanRelease(bean);
//    	relBean.setPostContent(content);
//        relBean.setThumbURL(imgs);
//
//        postRelease.createPostAsync(relBean, new BaseCall<MPostResp>() {
//            @Override
//            public void call(MPostResp resp) {
//                if (resp != null && resp.isRequestSuccess()) {
//
//                	MPostResp respSuccess = analyzeBeanSuccess(resp);
//                	respSuccess.setLocalPostId(relBean.getLocalPostId());
//                	if (relBean.getPostLevel() == 0) {
//                		startLocalData(HttpConstant.POST_RELEASE_UPDATE_ONE, GsonUtil.getGson().toJson(respSuccess), null);
//                    } else if (relBean.getPostLevel() == 1) {
//                    	startLocalData(HttpConstant.POST_DETAIL_UPDATE_SENDING_ONE, GsonUtil.getGson().toJson(respSuccess), null);
//                    }
//                	Intent intent = new Intent();
//                	intent.setAction(PostReleaseCallBack.MAINPOST_RELEASE_END);
//                	respSuccess.setSendState(PostReleaseCallBack.POST_RELEASE_SENDSUCCESS);
//                	Bundle bundle = new Bundle();
//                	bundle.putSerializable("RespData", respSuccess);
//                	intent.putExtras(bundle);
//                    mContext.sendBroadcast(intent);
//                    Slog.d("postReleaseBackground createPost sucess");
//                } else {
//                	if (bean.getPostLevel() == 0) {
//                		UpdatePostSendingState stateBean = new UpdatePostSendingState();
//                		stateBean.setLocalPostId(bean.getLocalPostId());
//                		stateBean.setLocalCreateTime(bean.getLocalCreateTime());
//                		stateBean.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                    	startLocalData(HttpConstant.POST_RELEASE_UPDATE_STATE_ONE, GsonUtil.getGson().toJson(stateBean), null);
//                    } else if (bean.getPostLevel() == 1) {
//                    	UpdatePostSendingState stateBean = new UpdatePostSendingState();
//                		stateBean.setLocalPostId(bean.getLocalPostId());
//                		stateBean.setLocalCreateTime(bean.getLocalCreateTime());
//                		stateBean.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                    	startLocalData(HttpConstant.POST_DETAIL_UPDATE_SENDING_STATE, GsonUtil.getGson().toJson(stateBean), null);
//                    }
//
//                	MPostResp respFailed = analyzeBeanSuccess(resp);
//                	respFailed.setLocalPostId(relBean.getLocalPostId());
//                	respFailed.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                	Intent intent = new Intent();
//                	intent.setAction(PostReleaseCallBack.MAINPOST_RELEASE_END);
//                	Bundle bundle = new Bundle();
//                	bundle.putSerializable("RespData", respFailed);
//                	intent.putExtras(bundle);
//                    mContext.sendBroadcast(intent);
//                    Slog.d("postReleaseBackground createPost failed");
//                }
//            }
//        });
//    }
//
//    private void updatePost(final PostReleaseReq bean, String content, List<String> imgs) {
//
//    	final PostReleaseReq relBean = analyzeBeanUpdate(bean);
//    	relBean.setPostContent(content);
//        relBean.setThumbURL(imgs);
//
//        postRelease.updatePostAsync(relBean, new BaseCall<MPostResp>() {
//            @Override
//            public void call(MPostResp resp) {
//                if (resp != null && resp.isRequestSuccess()) {
//
//                	MPostResp respSuccess = analyzeBeanSuccess(resp);
//                	respSuccess.setLocalPostId(relBean.getLocalPostId());
//                	if (relBean.getPostLevel() == 0) {
//                		startLocalData(HttpConstant.POST_RELEASE_UPDATE_ONE, GsonUtil.getGson().toJson(respSuccess), null);
//                	} else if (relBean.getPostLevel() == 1) {
//                    	startLocalData(HttpConstant.POST_DETAIL_UPDATE_SENDING_ONE, GsonUtil.getGson().toJson(respSuccess), null);
//                    }
//                	Intent intent = new Intent();
//                	intent.setAction(PostReleaseCallBack.MAINPOST_RELEASE_END);
//                	respSuccess.setSendState(PostReleaseCallBack.POST_RELEASE_SENDSUCCESS);
//                	Bundle bundle = new Bundle();
//                	bundle.putSerializable("RespData", respSuccess);
//                	intent.putExtras(bundle);
//                    mContext.sendBroadcast(intent);
//                    Slog.d("postReleaseBackground createPost sucess");
//                } else {
//                	if (bean.getPostLevel() == 0) {
//                		UpdatePostSendingState stateBean = new UpdatePostSendingState();
//                		stateBean.setLocalPostId(bean.getLocalPostId());
//                		stateBean.setLocalCreateTime(bean.getLocalCreateTime());
//                		stateBean.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                    	startLocalData(HttpConstant.POST_RELEASE_UPDATE_STATE_ONE, GsonUtil.getGson().toJson(stateBean), null);
//                    } else if (bean.getPostLevel() == 1) {
//                    	UpdatePostSendingState stateBean = new UpdatePostSendingState();
//                		stateBean.setLocalPostId(bean.getLocalPostId());
//                		stateBean.setLocalCreateTime(bean.getLocalCreateTime());
//                		stateBean.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                    	startLocalData(HttpConstant.POST_DETAIL_UPDATE_SENDING_STATE, GsonUtil.getGson().toJson(stateBean), null);
//                    }
//
//                	MPostResp respFailed = analyzeBeanSuccess(resp);
//                	respFailed.setLocalPostId(relBean.getLocalPostId());
//                	respFailed.setSendState(PostReleaseCallBack.POST_RELEASE_SENDFAILED);
//                	Intent intent = new Intent();
//                	intent.setAction(PostReleaseCallBack.MAINPOST_RELEASE_END);
//                	Bundle bundle = new Bundle();
//                	bundle.putSerializable("RespData", respFailed);
//                	intent.putExtras(bundle);
//                    mContext.sendBroadcast(intent);
//                    Slog.d("postReleaseBackground createPost failed");
//                }
//            }
//        });
//    }
//
//	private PostReleaseReq analyzeBeanImg(final PostReleaseReq bean, String content, List<String> imgs) {
//		PostReleaseReq newBean = new PostReleaseReq();
//
//		newBean.setTopicId(bean.getTopicId());
//		newBean.setTopicTitle(bean.getTopicTitle());
//		newBean.setPostId(bean.getPostId());
//		newBean.setLocalPostId(bean.getLocalPostId());
//		newBean.setPostTitle(bean.getPostTitle());
//		newBean.setParentId(bean.getParentId());
//		newBean.setPostLevel(bean.getPostLevel());
//		newBean.setToUserId(bean.getToUserId());
//		newBean.setSelectedToSolution(bean.getSelectedToSolution());
//		newBean.setEffect(bean.getEffect());
//		newBean.setPart(bean.getPart());
//		newBean.setSkin(bean.getSkin());
//		newBean.setLocalCreateTime(bean.getLocalCreateTime());
//
//		newBean.setPostContent(content);
//		newBean.setThumbURL(imgs);
//
//		return newBean;
//	}
//
//	private PostReleaseReq analyzeBeanRelease(PostReleaseReq bean) {
//		PostReleaseReq newBean = new PostReleaseReq();
//
//		newBean.setLocalPostId(bean.getLocalPostId());
//		newBean.setTopicId(bean.getTopicId());
//		newBean.setPostTitle(bean.getPostTitle());
//		newBean.setPostContent(bean.getPostContent());
//		newBean.setParentId(bean.getParentId());
//		newBean.setPostLevel(bean.getPostLevel());
//		newBean.setToUserId(bean.getToUserId());
//		newBean.setSelectedToSolution(bean.getSelectedToSolution());
//		newBean.setEffect(bean.getEffect());
//		newBean.setPart(bean.getPart());
//		newBean.setSkin(bean.getSkin());
//
//		return newBean;
//	}
//
//	private PostReleaseReq analyzeBeanUpdate(PostReleaseReq bean) {
//		PostReleaseReq newBean = new PostReleaseReq();
//
//		newBean.setLocalPostId(bean.getLocalPostId());
//		newBean.setTopicId(bean.getTopicId());
//		newBean.setPostId(bean.getPostId());
//		newBean.setPostTitle(bean.getPostTitle());
//		newBean.setPostContent(bean.getPostContent());
//		newBean.setParentId(bean.getParentId());
//		newBean.setPostLevel(bean.getPostLevel());
//		newBean.setToUserId(bean.getToUserId());
//		newBean.setSelectedToSolution(bean.getSelectedToSolution());
//		newBean.setEffect(bean.getEffect());
//		newBean.setPart(bean.getPart());
//		newBean.setSkin(bean.getSkin());
//
//		return newBean;
//	}

	private void startUpLocal(final String localRequestParams, final String localContent, final ClientCallback cltCallback) {
		try {
			if (callbackID > 999999999) {
				callbackID = 0;
			}
			mServer.startLocalData(localRequestParams, localContent, ++callbackID);
			//this.clientCallback = cltCallback;
			if (!mCallbackMap.isFull()) {
				if (cltCallback != null) {
					mCallbackMap.insert(callbackID, cltCallback);
				}
			} else {
				if (cltCallback != null) {
					String callback = resultStatus("{\"status\":\"FAILED\",\"msg\":\"call back queue is full\",\"ok\":true}", BaseResp.UNKNOWN, false);
					cltCallback.onSuccess(callback);
				}
			}
			Slog.d("startUpLocal cltCallback: " + cltCallback + " callbackID: " + callbackID);

		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public void cancelCallback(final int callBackId) {
		if (!mCallbackMap.isEmpty()) {
			mCallbackMap.remove(callBackId);
		}
	}

	private IRadarCallback.Stub mIRadarCallback = new IRadarCallback.Stub() {
		@Override
		public void onTestScriptResult(String serverResult, final int callBackId) throws RemoteException {
			Message msg = Message.obtain();
			msg = mHandler.obtainMessage(MSG_RESULT_CALLBACK, callBackId, 1, serverResult);
			Slog.d("onTestScriptResult serverResult:" + serverResult);
			mHandler.sendMessage(msg);
		}
	};

	private String resultStatus(String message, int statusCode, boolean isSuccess) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("message", message);
			jsonObject.put("statusCode", statusCode);
			jsonObject.put("success", isSuccess);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonObject.toString();
	}
	
	class CallbackMap    //回调map类
	{
		private int maxSize;  // 回调map长度，由构造函数初始化, 做一下限制
		private Map<Integer, Object> callBackParam;

		@SuppressLint("UseSparseArrays")
		public CallbackMap(int size)
		{
			maxSize = size;
			callBackParam = new HashMap<Integer, Object>();
		}

		public void insert(int callBackId, ClientCallback callBack)    // 添加回调
		{
			callBackParam.put(callBackId, callBack);
    		Slog.d("CallbackMap insert callBackId: " + callBackId + "  callBack: " + callBack);
    	}

		public void remove(int callBackId)    // 删除回调
		{
			Iterator<Integer> it = callBackParam.keySet().iterator();
			while(it.hasNext())
			{
				it = callBackParam.keySet().iterator();
				Integer Id = (Integer)it.next();
				if (Id == callBackId) {
					callBackParam.remove(callBackId);
					Slog.d("CallbackMap remove callBackId: " + callBackId);
					break;
				}
			}
		}
        
		public ClientCallback getEntry(int callBackId)    // 获取回调
		{
			Iterator<?> it = callBackParam.entrySet().iterator();
			ClientCallback callBack = null;
			while(it.hasNext())
			{
				@SuppressWarnings("unchecked")
                Entry<Integer, ?> currentEntry = (Entry<Integer, ?>) it.next();
            	
				if (currentEntry.getKey() == callBackId) {
					callBack = (ClientCallback) currentEntry.getValue();
					callBackParam.remove(callBackId);
					break;
				}
			}
			Slog.d("CallbackMap getEntry callBackId: " + callBackId + "  callBack: " + callBack);
			return callBack;
		}

		public boolean isEmpty()    // 判队列是否为空。若为空返回一个真值，否则返回一个假值。
		{
			return (callBackParam.size() == 0);
    	}

		public boolean isFull()    // 判断回调是否满
		{
			return (callBackParam.size() == maxSize);
		}

		public int size()    // 回调map的长度
		{
			return callBackParam.size();
		}
        
	}

}
